import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入页面组件
import Home from '@/views/Home.vue'
import FormDesigner from '@/views/FormDesigner.vue'
import FormRender from '@/views/FormRender.vue'
import FormPreview from '@/views/FormPreview.vue'
import GeneratedPage from '@/views/GeneratedPage.vue'
import TemplateManager from '@/views/TemplateManager.vue'
import PageManager from '@/views/PageManager.vue'
import DynamicPageView from '@/views/DynamicPageView.vue'
import PurePageView from '@/views/PurePageView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页'
    }
  },
  {
    path: '/designer',
    name: 'FormDesigner',
    component: FormDesigner,
    meta: {
      title: '表单设计器'
    }
  },
  {
    path: '/render',
    name: 'FormRender',
    component: FormRender,
    meta: {
      title: '表单渲染'
    }
  },
  {
    path: '/preview',
    name: 'FormPreview',
    component: FormPreview,
    meta: {
      title: '表单预览'
    }
  },
  {
    path: '/templates',
    name: 'TemplateManager',
    component: TemplateManager,
    meta: {
      title: '模板管理'
    }
  },
  {
    path: '/pages',
    name: 'PageManager',
    component: PageManager,
    meta: {
      title: '页面管理'
    }
  },
  {
    path: '/page/:routeName',
    name: 'GeneratedPage',
    component: GeneratedPage,
    meta: {
      title: '生成页面'
    },
    props: true
  },
  {
    path: '/view/:pageId',
    name: 'DynamicPageView',
    component: DynamicPageView,
    meta: {
      title: '动态页面'
    },
    props: true
  },
  {
    path: '/pure/:pageId',
    name: 'PurePageView',
    component: PurePageView,
    meta: {
      title: '纯页面'
    },
    props: true
  },
  {
    path: '*',
    redirect: '/'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫 - 设置页面标题
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = `${to.meta.title} - VForm2 表单设计器`
  }
  next()
})

// 动态路由加载 - 从localStorage加载生成的页面
function loadDynamicRoutes() {
  try {
    const pageList = JSON.parse(localStorage.getItem('simple-generated-pages') || '[]')
    
    pageList.forEach(page => {
      const routeName = page.routeName
      const existingRoute = router.options.routes.find(route => 
        route.path === `/page/${routeName}`
      )
      
      if (!existingRoute) {
        router.addRoute({
          path: `/page/${routeName}`,
          name: `GeneratedPage_${routeName}`,
          component: GeneratedPage,
          meta: {
            title: page.pageName || routeName
          },
          props: true
        })
      }
    })
  } catch (error) {
    console.error('加载动态路由失败:', error)
  }
}

// 初始化时加载动态路由
loadDynamicRoutes()

export default router
